import fs from "fs"
import path from "path"
import http from "http"
import mime from "mime"

const server = http.createServer((req, res) => {
    let { url, method } = req

    // 判断请求的地址是否是get并且是state开头
    if (method === 'GET' && url.startsWith('/state')) {
        // 获取请求文件的完整路径
        let filePath = path.join(process.cwd(), url)
        // 获取请求文件的类型
        let fileType = mime.getType(filePath)
        // 读取文件内容
        fs.readFile(filePath, (err, data) => {
            if (err) {
                res.writeHead(404, {
                    'Content-Type': 'text/html'
                })
                res.end('404 Not Found')
            } else {
                console.log("重新加载");

                res.writeHead(200, {
                    'Content-Type': fileType,
                    // 开启缓存
                    'Cache-Control': 'public, max-age=1000',
                })
                res.end(data)
            }
        })
    }

    // 处理其他接口请求
    if (["GET", "POST", "PUT", "DELETE"].includes(method) && url.startsWith('/api')) {
        // ......
        console.log("处理接口");
        res.writeHead(200, {
            'Content-Type': 'application/json'
        })
        res.end(JSON.stringify({
            code: 200,
            msg: 'success'
        }))
    }
})

server.listen(80, () => {
    console.log('server is running at http://localhost:80')
})